﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections.ObjectModel;

namespace FileSystemAudit
{
    public partial class Form1 : Form
    {
        private string folderToSave = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\FileSystemAudit";

        private bool isStartVolumetric;
        private bool isStartAudit;


        public Form1()
        {
            InitializeComponent();

            try
            {
                bgWorkerFileShareAudit.DoWork += new DoWorkEventHandler(bgWorkerFileShareAudit_DoWork);

                if (!Directory.Exists(folderToSave))
                {
                    Directory.CreateDirectory(folderToSave);
                }
            }
            catch
            {
                folderToSave = System.AppDomain.CurrentDomain.BaseDirectory;
            }
        }

        private void tabConfig_Leave(object sender, EventArgs e)
        {
            //save config
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    DataRow rwDetailsConfig = null; // this.dataSetConfiguration.Tables["Config"].NewRow();

                    rwDetailsConfig["nbYearAnalysis"] = (int)this.nbrYearForChangeAnalysis.Value;
                    rwDetailsConfig["nbTopExtensions"] = (int)this.nbrMostUsedExtension.Value;

                    rwDetailsConfig["extensionAsSourceCode"] = this.txBxExtensionCodeSourceFiles.Text;
                    rwDetailsConfig["extensionsAsApplication"] = this.txBxExtensionApplications.Text;

                    rwDetailsConfig["remarkableFileSize"] = this.remarkableFileSize.Value;

                    rwDetailsConfig["remarkableNbFilePerFolder"] = this.remarkableNbFilePerFolder.Value;

                    //this.dataSetConfiguration.Tables["Config"].Rows.Add(rwDetailsConfig);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Impossible to save line of config:" + ex.StackTrace);
                }

                //FileInfo fi = new FileInfo(folderToSave + "\\" + "data.xml");
                //StreamWriter sw = fi.CreateText();
                //sw.AutoFlush = true;

                //sw.Write(dataSetConfiguration.GetXml());

                //sw.Flush();
                //sw.Close();

            }
            catch (Exception exc)
            {
                MessageBox.Show("Impossible to save :" + exc.StackTrace);
            }
        }

        private void tabConfig_Enter(object sender, EventArgs e)
        {
            FileSystemDatabaseEntities datas= null ;
            try
            {
                datas = new FileSystemDatabaseEntities();
                var query = from folder in datas.FolderInfos where folder.Depth ==0 select folder;
                //dataGridViewOfRootFolderToScan.DataSource = 

            }
            catch (Exception exc)
            {
                MessageBox.Show("Impossible to load :" + exc.StackTrace);
            }
        }

        #region Folder Analysis

        private void btnLaunchFileShareAudit_Click(object sender, EventArgs e)
        {
            isStartAudit = !isStartAudit;

            if (isStartAudit)
            {
                btnLaunchFileShareAudit.Text = "Stop volumetric measures";

                bgWorkerFileShareAudit.RunWorkerAsync();
            }
            else
            {
                bgWorkerFileShareAudit.CancelAsync();

                btnLaunchFileShareAudit.Text = "Start volumetric measures";
            }
        }

        private void bgWorkerFileShareAudit_DoWork(object sender, DoWorkEventArgs e)
        {
            DataTable dtFolders = null; //  dataSetConfiguration.Tables["Folders"];

            //nous allons,pour chaque Path, chercher les informations suivantes:
            // 1 Taille totale
            //Top 10 des extensions au niveau de la taille totale
            // top 10 des extensions de fichier les + utilisé
            //les dossiers avec plus de 1000 fichiers
            //la taille des fichiers dépassant 20 Mb
            //

            // de même mesure de la profondeur de chaque dossier
            //Collection<FileAnalysisReport> FileAnalysisReportCollection = new Collection<FileAnalysisReport>();

            FolderCollection folders = new FolderCollection();
            folders = FolderCollection.Current;
            //DataTable dtFolders = dataSetConfiguration.Tables["Folders"];
            //enregistrement dans une table des actions sur les fichiers
            //un FileSystemWatcher pour chaque Path configuré.
            for (int f = 0; f < folders.Count; f++)
            {
                Folder folder = folders[f];

                //Analysis(folder.Path, ref FileAnalysisReportCollection);
            }
        }

        private void Analysis(string FolderPath, ref Collection<FileAnalysisReport> FileAnalysisReportCollection)
        {
            FileAnalysisReport res = new FileAnalysisReport();

            res.FolderPath = FolderPath;

            DirectoryInfo di = new DirectoryInfo(FolderPath);
            FileInfo[] files = di.GetFiles();

            res.NbrTotalFile = files.Length;

            List<string> extensions = new List<string>();

            for (int f = 0; f < files.Length; f++)
            {
                FileInfo fi = files[f];

                res.BiggerFiles.Add(fi.Length, fi.Length);

                if (extensions.Contains(fi.Extension))
                {
                    extensions.Add(fi.Extension);
                    res.MoreUsedExtension.Add(fi.Extension, 1);
                }
                else
                {
                    res.MoreUsedExtension[fi.Extension] = res.MoreUsedExtension[fi.Extension] + 1;
                }
            }

            FileAnalysisReportCollection.Add(res);

            DirectoryInfo[] directories = di.GetDirectories();
            for (int f = 0; f < directories.Length; f++)
            {
                Analysis(directories[f].FullName, ref FileAnalysisReportCollection);
            }
        }

        #endregion

        #region Volumetry

        private void btnStartVolumetric_Click(object sender, EventArgs e)
        {
            isStartVolumetric = !isStartVolumetric;

            if (isStartVolumetric)
            {
                btnStartVolumetric.Text = "Stop volumetric measures";

                bgWorkerVolumetry.RunWorkerAsync();
            }
            else
            {
                bgWorkerVolumetry.CancelAsync();

                btnStartVolumetric.Text = "Start volumetric measures";
            }
        }

        private void bgWorkerVolumetry_DoWork(object sender, DoWorkEventArgs e)
        {
            FolderCollection folders = new FolderCollection();
            folders = FolderCollection.Current;
            //DataTable dtFolders = dataSetConfiguration.Tables["Folders"];
            //enregistrement dans une table des actions sur les fichiers
            //un FileSystemWatcher pour chaque Path configuré.
            for (int f = 0; f < folders.Count; f++)
            {
                Folder folder = folders[f];

                FileSystemWatcher fsw = new FileSystemWatcher(folder.Path);
                fsw.Changed += new FileSystemEventHandler(fsw_Changed);

                folders[f].fsw = fsw; // new FileSystemWatcher(folders[f].Path);

            }
        }

        protected internal void fsw_Changed(object sender, FileSystemEventArgs e)
        {

            DataRow folderAcces = null; //  FolderAudit.NewRow();
            //folderAcces = dsReporting.Tables[FolderAudit.TableName].NewRow();

            folderAcces["FolderPath"] = e.FullPath;
            folderAcces["ActionDate"] = DateTime.Now;

            folderAcces["ActionType"] = Enum.GetName(typeof(WatcherChangeTypes), e.ChangeType);

            string target = e.Name;
            bool isFile = false;

            if (File.Exists(target))
            {
                isFile = true;

                folderAcces["IsFile"] = isFile;
                folderAcces["FilePath"] = target;
            }

            
        }

        private void EndVolumetryWork()
        {
            string infoDate = DateTime.Now.ToShortDateString().Replace("/", "").Trim() + "_" + DateTime.Now.ToShortTimeString().Replace(":", "").Trim();
            string volumetricDataFolder = folderToSave + "\\" + infoDate;

            if (!Directory.Exists(volumetricDataFolder))
                Directory.CreateDirectory(volumetricDataFolder);

            string volumetricDataFile = volumetricDataFolder + "\\" + "Voumetric.xml";

            //dsReporting.WriteXml(volumetricDataFile);
        }
        #endregion

        private void singleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (folderDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = folderDiag.SelectedPath;

            }
        }
    }
}
